<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

JFX::checkAdminPermsRedirect('core', 'perm_publish_workspaces');

// just to be clear what variables are of interest to this script
$fromWorkspaceId = $fromId;
$toWorkspaceId = $toId;
$fromPageId = $fromPageId;
$toPageId = $toPageId;
$deleteDeadPages = $deleteDeadPages;


// lets begin our copy
if($fromPageId == 0){
    // get the default domain
    $domainid = $DB->oneValue($CONFIG->dbprefix.'domains', 'id', "is_default = 1");
    if($domainid == 0){
        JFX::addError($this->lang('no_default_domain'));
        return;
    }
    $pageid = (int) $DB->oneValue($CONFIG->dbprefix.'pages', 'id', "domain_id = '{$domainid}' AND workspace_id = '{$fromWorkspaceId}' AND parent_id = 0");
    if($pageid == 0){
        JFX::addError($this->lang('invalid_domain_copy_from'));
        return;
    }
    $fromPageId = $pageid;
}
$fromPageData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}pages WHERE id = '{$fromPageId}'");
$fromPageData['subpages'] = JFX::getPageTree($fromPageId, $fromWorkspaceId);

/*
if($toPageId == 0){
    // get the default domain
    $domainid = $DB->oneValue($CONFIG->dbprefix.'domains', 'id', "is_default = 1");
    if($domainid == 0){
        JFX::addError('Could not find a default domain, please visit the domains configuration and set a domain to be the default');
        return;
    }
    $pageid = (int) $DB->oneValue($CONFIG->dbprefix.'pages', 'id', "domain_id = '{$domainid}' AND workspace_id = '{$toWorkspaceId}' AND parent_id = 0");
    if($pageid == 0){
        // try to get the domain from the live workspace
        $pageid = (int) $DB->oneValue($CONFIG->dbprefix.'pages', 'id', "domain_id = '{$domainid}' AND workspace_id = '1' AND parent_id = 0");
        if($pageid == 0){
            JFX::addError('Could not find the domain to copy to, expecting to find a page assigned to the domain "'.$DB->oneValue($CONFIG->dbprefix.'domains', 'domain_name', "id = '{$domainid}'").'"');
            return;
        }
        // now copy the domain to the workspace
        $copyPageId = $pageid;
        /*
        $dbParams = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}pages WHERE id = '{$copyPageId}'");
        unset($dbParams['id']);
        $dbParams['workspace_id'] = $toWorkspaceId;
        $pageid = $DB->insert($CONFIG->dbprefix.'pages', $dbParams);
        $blocks = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE workspace_id = '{$fromWorkspaceId}' AND parent_id = 'page_{$copyPageId}' AND page_parent = 1");
        $block = new JFX_Block;
        foreach($blocks as $k=>$v){
            $block->loadById($v['id'], $fromWorkspaceId, true, false);
            $block->copy($pageid, $toWorkspaceId);
        }
         * 
         *
    }
    $toPageId = $pageid;
}
*/


//$DB->debug(true);
//$DB->showErrors(true);
if(JFX_DoCopyWorkspace_CopyPage($fromPageData, $toPageId, $toWorkspaceId, $deleteDeadPages)){

    JFX::addSuccess($this->lang('page_copy_success'));

}
//$DB->debug(false);
//$DB->showErrors(false);








function JFX_DoCopyWorkspace_CopyPage($fromPageData, $toPageId, $newWorkspaceId, $deleteDeadPages=false){
    
    $DB = JFX::registry('db');
    $USER = JFX::registry('JFX_User');
    $LANG = JFX::registry('lang');
    $CONFIG = JFX::registry('config');
    $doneSubPages = array();
    //$fromPageData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}pages WHERE id = '{$fromPageId}'");
    $toPageData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}pages WHERE id = '{$toPageId}'");
    $fromDomainId = $fromPageData['domain_id'];
    $fromSubPages = $fromPageData['subpages'];

    if($fromPageData['is_default']==1){
        // remove the pre-existing default page
        $DB->update($CONFIG->dbprefix.'pages', array('is_default'=>0), "workspace_id = '{$newWorkspaceId}' AND domain_id = '{$fromPageData['domain_id']}'");
    };

    if($DB->countRows($CONFIG->dbprefix.'pages', "slug = '{$fromPageData['slug']}' AND domain_id = '{$fromPageData['domain_id']}' AND workspace_id = '{$newWorkspaceId}'")>0){
        // the page already exists, lets update it

        $toParentData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}pages WHERE slug = '{$fromPageData['slug']}' AND domain_id = '{$fromPageData['domain_id']}' AND workspace_id = '{$newWorkspaceId}'");
        if($toParentData['id'] == $toPageId && $toParentData['parent_id'] != 0){
            JFX::addError($this->foldLang('could_not_copy_into_sub', $LANG->getContent('core', 'heading', $toPageId, '', $newWorkspaceId)));
            return false;
        }
        if($toParentData['parent_id'] == 0){
            $toParentId = 0;
            $langPageId = $toParentData['id'];
        }else{
            $toParentId = $toParentData['id'];
            $langPageId = $toParentData['id'];
        }
        $dbParams = array(
            'parent_id' => $toPageId,
            'slug' => $fromPageData['slug'],
            'is_published' => $fromPageData['is_published'],
            'is_default' => $fromPageData['is_default'],
            'domain_id' => $fromPageData['domain_id'],
            'sorting' => $fromPageData['sorting']
        );
        $DB->update($CONFIG->dbprefix.'pages', $dbParams, "id = '{$toParentId}'");
        // delete the blocks as they are copied afterwards
        $block = new JFX_Block;
        $blocks = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE workspace_id = '{$newWorkspaceId}' AND page_id = '{$toParentId}' AND page_parent = 1 ORDER BY sorting ASC");
        foreach($blocks as $k=>$v){
            $block->loadById($v['id'], $toParentId, $v['workspace_id'], true, true);
            $block->delete();
        }
        $toParentId = $toParentData['id'];
    }else{
        // have to insert the page
        
        $toParentData = array(
            'parent_id' => $toPageId,
            'slug' => $fromPageData['slug'],
            'is_published' => $fromPageData['is_published'],
            'workspace_id' => $newWorkspaceId,
            'owner_id' => $USER->userid,
            'created_tstamp' => time(),
            'modified_tstamp' => time(),
            'is_default' => $fromPageData['is_default'],
            'domain_id' => $fromPageData['domain_id'],
            'sorting' => $fromPageData['sorting']
        );
        $toParentId = $DB->insert($CONFIG->dbprefix.'pages', $toParentData);
        $toParentData['id'] = $toParentId;
    }
//die('done');
    // update the language
    $title = $LANG->getContent('core', 'heading', $fromPageData['id'], 'en_US', $fromPageData['workspace_id']);
    $LANG->updateContent('core', 'heading', $toParentId, $title, '*', $newWorkspaceId);

    $menu = $LANG->getContent('core', 'page_menu', $fromPageData['id'], 'en_US', $fromPageData['workspace_id']);
    $LANG->updateContent('core', 'page_menu', $toParentId, $menu, '*', $newWorkspaceId);

    $content = $LANG->getContent('core', 'page_content', $fromPageData['id'], 'en_US', $fromPageData['workspace_id']);
    $LANG->updateContent('core', 'page_content', $toParentId, $content, '*', $newWorkspaceId);

    // copy the blocks
    $block = new JFX_Block;
    $blocks = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE workspace_id = '{$fromPageData['workspace_id']}' AND page_id = '{$fromPageData['id']}' AND page_parent = 1 ORDER BY sorting ASC");
    foreach($blocks as $k=>$v){
        $block->loadById($v['id'], $fromPageData['id'], $v['workspace_id'], true, true);
        $block->copy($toParentId, $newWorkspaceId);
    }
    // now do the sub pages
    $toSubPages = JFX::getPageTree($toParentData['id'], $newWorkspaceId);
    foreach($fromSubPages as $k=>$v){
        $doneSubPages[] = $v['slug'];
        //JFX_DoCopyWorkspace_CopyPage($v, $toParentData['id'], $newWorkspaceId, $deletePages);
    JFX_DoCopyWorkspace_CopyPage($v, $toParentId, $newWorkspaceId, $deletePages);

    }
    if($deleteDeadPages){
        foreach($toSubPages as $k=>$v){
            $slug = $DB->oneValue($CONFIG->dbprefix.'pages', 'slug', "id = '{$v}'");
            $block = new JFX_Block;
            if(!in_array($v['id'], $doneSubPages)){
                JFX_DoCopyWorkspace_DeletePage($v['id'], $newWorkspaceId);
            }
            
        }
    }
}





function JFX_DoCopyWorkspace_DeletePage($pageid, $workspaceid){
    $block = new JFX_Block;
    $blocks = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}blocks WHERE parent_id = 'jfxpage-{$pageid}' AND workspace_id = '{$workspaceid}' AND page_id = '{$pageid}'");
    foreach($blocks as $key => $value){
        $block->loadById($value, $pageid, $newWorkspaceId, true, true);
        $block->delete();
    }
    $subpages = JFX::getPageTree($pageid, $workspaceid, false);
    foreach($subpages as $k=>$v){
        JFX_DoCopyWorkspace_DeletePage($v['id'], $workspaceid);
    }
    $DB->delete($CONFIG->dbprefix.'pages', "id = '{$pageid}' AND workspace_id = '{$workspaceid}'");
}



